<template>
  <div id="app">
    <div id="up_div">
      <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

          <el-form-item label="入库状态" prop="inboundStatus">
            <el-radio-group v-model="queryParams.inboundStatus"  @change="handleQuery">
              <el-radio-button
                v-for="item in inboundStatus"
                :key="item.value"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="入库类型" prop="inboundType">
            <el-radio-group v-model="queryParams.inboundType" @change="handleQuery">
              <el-radio-button
                v-for="item in inboundType"
                :key="item.value"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="入库单号" prop="inboundOrderNo">
            <el-input
              v-model="queryParams.inboundOrderNo"
              placeholder="请输入入库单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="订单编号" prop="orderNo">
            <el-input
              v-model="queryParams.orderNo"
              placeholder="请输入订单编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div id="down_div">
      <div class="app-container">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="addWmsInbound"
              v-hasPermi="['system:wmsInbound:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:wmsInbound:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:wmsInbound:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:wmsInbound:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="wmsInboundList" @selection-change="handleSelectionChange" stripe>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="expand" >
            <template #default="props">
              <h3>商品明细</h3>
              <el-divider></el-divider>
              <el-table :data="props.row.inventoryHistoryList" border>
                <el-table-column
                  prop="productName"
                  label="商品名称"
                  width="180">
                </el-table-column>
                <el-table-column label="商品编码" align="center" prop="productCode" />
                <el-table-column label="规格型号" align="center" prop="productSpec" />
                <el-table-column label="单位" align="center" prop="productUnit" >
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.wms_product_unit" :value="scope.row.productUnit">
                    </dict-tag>
                  </template>
                </el-table-column>
                <el-table-column label="商品单价" align="center" prop="unitPrice" />
                <el-table-column label="商品数量" align="center" prop="totalQuantity" />
                <el-table-column label="商品总价" align="center" prop="totalAmount" />
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="入库单号" align="center" prop="inboundOrderNo" />
          <el-table-column label="订单编号" align="center" prop="orderNo" />
          <el-table-column label="入库类型" align="center" prop="inboundType" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_inbound_type" :value="scope.row.inboundType">
              </dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="入库状态" align="center" prop="inboundStatus" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_inbound_status" :value="scope.row.inboundStatus">
              </dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="供应商" align="center" prop="supplierId" >
            <template slot-scope="scope">
              {{ getSelectLabel(supplierSelect,scope.row.supplierId) }}
            </template>
          </el-table-column>
          <el-table-column label="仓库" align="center" prop="warehouseId" >
            <template slot-scope="scope">
              {{ getSelectLabel(warehouseSelect,scope.row.warehouseId) }}
            </template>
          </el-table-column>
          <el-table-column label="库区" align="center" prop="warehouseAreaId" >
            <template slot-scope="scope">
              {{ getSelectLabel(warehouseAreaSelect,scope.row.warehouseAreaId) }}
            </template>
          </el-table-column>
          <el-table-column label="货架" align="center" prop="warehouseRackId"  >
            <template slot-scope="scope">
              {{ getSelectLabel(warehouseRackSelect,scope.row.warehouseRackId) }}
            </template>
          </el-table-column>
          <el-table-column label="货位" align="center" prop="warehouseLocationId" >
            <template slot-scope="scope">
              {{ getSelectLabel(warehouseLocationSelect,scope.row.warehouseLocationId) }}
            </template>
          </el-table-column>
          <el-table-column label="合计金额" align="center" prop="totalAmount" />
          <el-table-column label="数量" align="center" prop="totalQuantity" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="入库人员" align="center" prop="nickName" />
          <el-table-column label="入库时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="入库信息二维码" align="center" prop="barcodeImageUrl" width="100px">
            <template slot-scope="scope">
              <image-preview :src="dispose(scope.row.barcodeImageUrl)" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right"  class-name="small-padding fixed-width" width="140px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-ic
                on-edit"
                @click="handleUpdate(scope.row)"
                :disabled="scope.row.inboundStatus !== '2'"
                v-hasPermi="['system:wmsInbound:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                :disabled="scope.row.inboundStatus === '1'"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:wmsInbound:remove']"
              >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-close"
                :disabled="scope.row.inboundStatus !== '2'"
                @click="cancellation(scope.row)"
                v-hasPermi="['system:wmsInbound:remove']"
              >作废</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-printer"
                @click="handlePrint(scope.row)"
                :disabled="scope.row.inboundStatus !== '1'"
                v-hasPermi="['system:wmsInbound:print']"
              >打印</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>


    <!-- 隐藏的打印模板区域 -->
    <div ref="printSection" style="display:none; font-family: 'Microsoft Yahei', Arial, sans-serif; font-size: 14px; width: 800px; padding: 20px; box-sizing: border-box;">

      <!-- 打印头部 -->
      <div class="print-header" style="text-align: center; margin-bottom: 20px;">
        <h2 style="margin-bottom: 8px;">入库单详情</h2>
        <p>打印时间：{{ currentTime }}</p>
      </div>

      <!-- 上半部分两列 -->
      <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">

        <!-- 左列 -->
        <div style="width: 48%; line-height: 28px;">
          <p><strong>入库单号：</strong> {{ printData.inboundOrderNo }}</p>
          <p><strong>订单编号：</strong> {{ printData.orderNo }}</p>
          <p><strong>入库类型：</strong> {{ getDictLabel('wms_inbound_type', printData.inboundType) }}</p>
          <p><strong>入库状态：</strong> {{ getDictLabel('wms_inbound_status', printData.inboundStatus) }}</p>
          <p><strong>供应商：</strong> {{ getSelectLabel(supplierSelect, printData.supplierId) }}</p>
          <p><strong>仓库：</strong> {{ getSelectLabel(warehouseSelect, printData.warehouseId) }}</p>
          <p><strong>库区：</strong> {{ getSelectLabel(warehouseAreaSelect, printData.warehouseAreaId) }}</p>
          <p><strong>货架：</strong> {{ getSelectLabel(warehouseRackSelect, printData.warehouseRackId) }}</p>
        </div>

        <!-- 右列 -->
        <div style="width: 48%; line-height: 28px;">
          <p><strong>货位：</strong> {{ getSelectLabel(warehouseLocationSelect, printData.warehouseLocationId) }}</p>
          <p><strong>备注：</strong> {{ printData.remark || '-' }}</p>
          <p><strong>入库时间：</strong> {{ parseTime(printData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</p>
          <p><strong>合计金额：</strong> {{ printData.totalAmount }}</p>
          <p><strong>数量：</strong> {{ printData.totalQuantity }}</p>
          <p><strong>入库人员：</strong> {{ printData.nickName }}</p>
        </div>

      </div>

      <!-- 下半部分：商品明细表格 -->
      <h3 style="margin-bottom: 8px;">商品明细</h3>
      <el-divider style="margin-bottom: 10px;"></el-divider>
      <table border="1" cellspacing="0" cellpadding="6" style="width: 100%; border-collapse: collapse; font-size: 13px;">
        <thead style="background-color: #f5f7fa;">
        <tr>
          <th>商品名称</th>
          <th>商品编码</th>
          <th>规格型号</th>
          <th>单位</th>
          <th>商品单价</th>
          <th>商品数量</th>
          <th>商品总价</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, idx) in printData.inventoryHistoryList" :key="idx">
          <td>{{ item.productName }}</td>
          <td style="text-align:center;">{{ item.productCode }}</td>
          <td style="text-align:center;">{{ item.productSpec }}</td>
          <td style="text-align:center;">{{ getDictLabel('wms_product_unit', item.productUnit) }}</td>
          <td style="text-align:right;">{{ item.unitPrice }}</td>
          <td style="text-align:right;">{{ item.totalQuantity }}</td>
          <td style="text-align:right;">{{ item.totalAmount }}</td>
        </tr>
        </tbody>
      </table>

      <!-- 底部 -->
      <div style="display: flex; justify-content: space-between; margin-top: 20px; font-size: 14px;">
        <div class="print-footer" style="line-height: 28px;">
          <p><strong>合计金额：</strong> {{ printData.totalAmount }}</p>
          <p><strong>合计数量：</strong> {{ printData.totalQuantity }}</p>
        </div>
        <div style="width: 300px; height: 100px; text-align: center;">
          <p style="margin: 0 0 6px 0; font-weight: bold;">入库信息二维码</p>
          <img :src="printData.barcodeImageUrl" alt="二维码" style="width: 100%; height: 100%;" />
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import {
  listWmsInbound,
  getWmsInbound,
  delWmsInbound,
  addWmsInbound,
  updateWmsInboun,
  getInboundOrderNo,
  updateWmsInbound
} from "@/api/system/wmsInbound"
import AddWmsInbound from "./addWmsInbound"
import { getSupplierSelect,
  getWarehouseAreaSelect,
  getWarehouseSelect,
  getWarehouseRackSelect,
  getWmsWarehouseLocationSelect }  from "@/api/system/selectVo"
import printJS from 'print-js'
import {cancellation} from "@/api/system/wmsTransfer";


export default {
  name: "WmsInbound",
  dicts:["wms_inbound_type","wms_inbound_status","wms_product_unit"],
  components: {AddWmsInbound},
  data() {
    return {
      currentComponent: '',
      // 遮罩层
      loading: true,
      inboundStatus:[
        {
          "value":"",
          "label":"全部"
        },
        {
          "value":"1",
          "label":"已入库"
        },
        {
          "value":"2",
          "label":"待入库"
        },
        {
          "value":"3",
          "label":"作废"
        },
      ],
      inboundType:[

        {
          "value":"",
          "label":"全部"
        },
        {
          "value":"1",
          "label":"采购入库"
        },
        {
          "value":"2",
          "label":"生产入库"
        },
        {
          "value":"3",
          "label":"退货入库"
        },
        {
          "value":"4",
          "label":"归还入库"
        },
      ],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库信息表格数据
      wmsInboundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inboundOrderNo: null,
        orderNo: null,
        inboundType: "",
        inboundStatus: "",
        supplierId: null,
        warehouseId: null,
        warehouseAreaId: null,
        warehouseRackId: null,
        warehouseLocationId: null,
        totalAmount: null,
        totalQuantity: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        inboundOrderNo: [
          { required: true, message: "入库单号不能为空", trigger: "blur" }
        ],
        inboundType: [
          { required: true, message: "入库类型不能为空", trigger: "change" }
        ],
        inboundStatus: [
          { required: true, message: "入库状态不能为空", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "仓库id不能为空", trigger: "blur" }
        ],
        warehouseAreaId: [
          { required: true, message: "库区id不能为空", trigger: "blur" }
        ],
      },
      supplierSelect:[],
      warehouseAreaSelect:[],
      warehouseSelect:[],
      warehouseRackSelect:[],
      warehouseLocationSelect:[],

      printData: {},      // 当前打印行数据
      currentTime: '',    // 打印时间
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询入库信息列表 */
    getList() {
      this.loading = true
      this.getSelect();

      listWmsInbound(this.queryParams).then(response => {
        this.wmsInboundList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    //获取下关的下拉框
    getSelect(){
      getSupplierSelect().then(response => {
        this.supplierSelect = response.data
      });
      getWarehouseAreaSelect().then(response => {
        this.warehouseAreaSelect = response.data
      });
      getWarehouseSelect().then(response => {
        this.warehouseSelect = response.data
      });
      getWarehouseRackSelect().then(response => {
        this.warehouseRackSelect = response.data
      });
      getWmsWarehouseLocationSelect().then(response => {
        this.warehouseLocationSelect = response.data
      });
    },

    /*getSelectLabel(select,id) {
      const supplier = select.find(item => item.value === id);
      return supplier ? supplier.label : id; // 找不到则显示原始ID
    },*/


    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        inboundOrderNo: null,
        orderNo: null,
        inboundType: null,
        inboundStatus: null,
        supplierId: null,
        warehouseId: null,
        warehouseAreaId: null,
        warehouseRackId: null,
        warehouseLocationId: null,
        totalAmount: null,
        totalQuantity: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      //判断选中的数据的入库状态是入库则禁止修改
      if(selection.length==1){
        this.single = selection[0].inboundStatus==='1'
      }
      this.multiple = !selection.length
    },

    addWmsInbound(){
      getInboundOrderNo().then(response => {
        var inboundOrderNo = response.data.inboundOrderNo

        this.$emit("goNextStep",inboundOrderNo)
        }
      )
    },

    /** 作废按钮操作 */
    cancellation(row) {
      const param = {
        id : row.id,
        inboundStatus: "3"
      }
      this.$modal.confirm('是否确认作废盘库信息编号为"' + row.inboundOrderNo + '"的数据项？').then(function() {
        return updateWmsInbound(param)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("作废成功")
      }).catch(() => {})
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getWmsInbound(id).then(response => {
        this.$emit("goNextEdit",response.data)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWmsInbound(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addWmsInbound(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids

      // 检查是否包含不可删除的状态
      const itemsToDelete = Array.isArray(this.ids) ?
        this.wmsInboundList.filter(item => this.ids.includes(item.id)) :
        [row];

      const hasCompletedItems = itemsToDelete.some(item => item.inboundStatus === "1");

      if (hasCompletedItems) {
        this.$modal.msgError("已入库的记录不能删除");
        return;
      }

      var hint = '是否确认删除入库单号为"' + row.inboundOrderNo + '"的数据项？';
      if(this.ids.length>0){
        hint = '是否确认删除入选中的数据项？';
      }

      this.$modal.confirm(hint).then(function() {
        return delWmsInbound(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/wmsInbound/export', {
        ...this.queryParams
      }, `wmsInbound_${new Date().getTime()}.xlsx`)
    },


    handlePrint(row) {
      // 深拷贝，避免污染表格中显示的原始数据
      this.printData = JSON.parse(JSON.stringify(row));
      if (this.printData.barcodeImageUrl){
        this.printData.barcodeImageUrl = process.env.VUE_APP_BASE_API+this.printData.barcodeImageUrl;

      }
      this.currentTime = this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
      this.$nextTick(() => {
        printJS({
          printable: this.$refs.printSection.innerHTML,
          type: 'raw-html',
          style: `
            body { font-family: 'Microsoft Yahei', Arial, sans-serif; font-size: 14px; }
            table, th, td { border: 1px solid #ddd; border-collapse: collapse; }
            th, td { padding: 6px; }
            th { background-color: #f5f7fa; }
          `
        })
      })
    },

    getDictLabel(dictType, value) {
      const dict = this.dict.type[dictType] || []
      const item = dict.find(d => d.value === value)
      return item ? item.label : (value || '-')
    },

    getSelectLabel(selectList, id) {
      if (!selectList || !id) return '-'
      const item = selectList.find(i => i.value === id)
      return item ? item.label : (id || '-')
    },

    parseTime(time, format) {
      if (!time) return '-'
      const date = new Date(time)
      const y = date.getFullYear()
      const m = (date.getMonth() + 1).toString().padStart(2, '0')
      const d = date.getDate().toString().padStart(2, '0')
      const h = date.getHours().toString().padStart(2, '0')
      const i = date.getMinutes().toString().padStart(2, '0')
      const s = date.getSeconds().toString().padStart(2, '0')
      return `${y}-${m}-${d} ${h}:${i}:${s}`
    },
    dispose(val){
      return process.env.VUE_APP_BASE_API+val;
    },
  }
}
</script>
<style>
body, html {
  margin: 0;
  padding: 0;
  height: 100%;
}

#app {
  //background-color: #f4f4f4;
  background-color: #ffffff;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 3px;
}

#up_div {
  background-color: white;
  height: 30%;
  width: 100%;
  margin-bottom: 20px; /* Space between the two divs */
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px; /* Optional rounded corners */
}

#down_div {
  background-color: white;
  height: 70%;
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px; /* Optional rounded corners */
}

/* 可根据需要调整打印区样式 */
.print-header h2 {
  font-weight: bold;
}

.print-footer p {
  margin: 4px 0;
}
</style>
